<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import type { Ref } from 'vue';
import { ref } from 'vue';
import { fetchDeleteDept, fetchGetDeptList } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { enableStatusRecord } from '@/constants/business';
import DeptOperateDrawer, { type OperateType } from './modules/dept-operate-drawer.vue';
import DeptSearch from './modules/dept-search.vue';

const appStore = useAppStore();

const { columns, columnChecks, data, loading, getData, getDataByPage, pagination, searchParams, resetSearchParams } =
  useTable({
    apiFn: fetchGetDeptList,
    apiParams: {
      current: 1,
      size: 10,
      // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
      // the value can not be undefined, otherwise the property in Form will not be reactive
      deptName: null
    },
    columns: () => [
      {
        key: 'deptName',
        title: '部门名称',
        align: 'left',
        minWidth: 120
      },
      {
        key: 'treeSort',
        title: '部门排序',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'status',
        title: '状态',
        align: 'center',
        width: 100,
        render: row => {
          if (row.status === null) {
            return null;
          }

          const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
            0: 'success',
            1: 'warning'
          };

          const label = $t(enableStatusRecord[row.status]);

          return <NTag type={tagMap[row.status]}>{label}</NTag>;
        }
      },
      {
        key: 'operate',
        title: $t('common.operate'),
        align: 'center',
        width: 220,
        render: row => (
          <div class="flex-center gap-8px">
            <NButton type="primary" ghost size="small" onClick={() => handleAddChildMenu(row)}>
              新增子部门
            </NButton>

            <NButton type="primary" ghost size="small" onClick={() => handleEdit(row)}>
              {$t('common.edit')}
            </NButton>
            <NPopconfirm onPositiveClick={() => handleDelete(row.id!)}>
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton type="error" ghost size="small" disabled={row.id === 1}>
                    {$t('common.delete')}
                  </NButton>
                )
              }}
            </NPopconfirm>
          </div>
        )
      }
    ]
  });

const {
  drawerVisible,
  // editingData,
  // handleAdd,
  // handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted,
  openDrawer
  // closeDrawer
} = useTableOperate(data, getData);

async function handleBatchDelete() {
  // request
  console.log(checkedRowKeys.value);

  onBatchDeleted();
}

async function handleDelete(id: number) {
  const { error } = await fetchDeleteDept(id);
  if (!error) {
    onDeleted();
  }
}

// 操作类型，新增了添加子节点的
const operateType = ref<OperateType>('add');

const editingData: Ref<Api.System.Dept | null> = ref(null);

// 新增
function handleAdd() {
  operateType.value = 'add';
  openDrawer();
}

// 编辑
function handleEdit(item: Api.System.Dept) {
  operateType.value = 'edit';
  editingData.value = { ...item };

  openDrawer();
}

// 新增子部门
function handleAddChildMenu(item: Api.System.Dept) {
  operateType.value = 'addChild';
  editingData.value = { ...item };
  openDrawer();
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <DeptSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <NCard title="部门管理" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="true"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>

      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1088"
        :loading="loading"
        :row-key="row => row.id"
        remote
        :pagination="pagination"
        class="sm:h-full"
      />

      <DeptOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
